package models

import (
	"errors"
	//"github.com/astaxie/beego/logs"
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
	"lottery/libs/mymgo"
)

const (
	TEARMDICT_COL_STR = "tearmdict"
)

type TearmDict struct {
	Id             int64  `json:"id" bson:"_id"`
	Platform1Id    int    `json:"platform1Id" bson:"platform1Id"`       //平台1ID
	Platform2Id    int    `json:"platform2Id" bson:"platform2Id"`       //平台2ID
	Platform1Tearm string `json:"platform1Tearm" bson:"platform1Tearm"` //平台1球队名称
	Platform2Tearm string `json:"platform2Tearm" bson:"platform2Tearm"` //平台1球队名称
	IsDeleted      bool   `json:"isDeleted" bson:"isDeleted"`
	CreateTime     int64  `json:"createTime" bson:"createTime"`
}

func ExistsTearm(tearmdict *TearmDict) (exist bool) {
	sess, err := mymgo.OpenBase()
	if err != nil {
		return
	}

	return sess.Exist(TEARMDICT_COL_STR, bson.M{
		"platform1Id":    tearmdict.Platform1Id,
		"platform2Id":    tearmdict.Platform2Id,
		"platform1Tearm": tearmdict.Platform1Tearm,
		"platform2Tearm": tearmdict.Platform2Tearm,
	})
}

func SaveTearm(tearmdict *TearmDict) (err error) {
	sess, err := mymgo.OpenBase()
	if err != nil {
		return
	}

	if ExistsTearm(tearmdict) {
		return
	}
	tearmdict.Id = int64(sess.AutoIncId(TEARMDICT_COL_STR))

	return sess.Insert(TEARMDICT_COL_STR, tearmdict)
}

func SaveTearmArr(tearmdicts []*TearmDict) (err error) {
	sess, err := mymgo.OpenBase()
	if err != nil {
		return
	}
	for _, tearmdict := range tearmdicts {
		if ExistsTearm(tearmdict) {
			continue
		}
		tearmdict.Id = int64(sess.AutoIncId(TEARMDICT_COL_STR))

		err = sess.Insert(TEARMDICT_COL_STR, tearmdict)

		if err != nil {
			break
		}
	}
	return
}

func GetTearmList() (tearms []*TearmDict, err error) {

	sess, err := mymgo.OpenBase()
	if err != nil {
		return
	}

	tearms = make([]*TearmDict, 0, 50)

	err = sess.WithC(TEARMDICT_COL_STR, func(col *mgo.Collection) error {
		return col.Find(bson.M{"isDeleted": false}).All(&tearms)
	})
	return
}

func DelTearmById(id int64) (err error) {
	sess, err := mymgo.OpenBase()
	if err != nil {
		return
	}

	return sess.UpdateId(TEARMDICT_COL_STR, id, bson.M{
		"$set": bson.M{
			"isDeleted": true,
		},
	})
}

func DelTearmByTearm(tearm *TearmDict) (err error) {
	err = nil
	if !ExistsTearm(tearm) {
		return
	}

	sess, err := mymgo.OpenBase()
	if err != nil {
		return
	}

	return sess.Remove(TEARMDICT_COL_STR, bson.M{
		"platform1Id":    tearm.Platform1Id,
		"platform2Id":    tearm.Platform2Id,
		"platform1Tearm": tearm.Platform1Tearm,
		"platform2Tearm": tearm.Platform2Tearm,
	})
}

func UpdataTearm(tearm *TearmDict) (err error) {

	sess, err := mymgo.OpenBase()
	if err != nil {
		return
	}

	if tearm.Id <= 0 {
		err = errors.New("id不能为空")
		return
	}

	return sess.UpdateId(TEARMDICT_COL_STR, tearm.Id, &tearm)
}
